import logging
import pytest
from bs4 import BeautifulSoup
from config import datas
from common.request_util_test import RequestUtil
from common.test_yaml_util_test import YamlUtil


class TestLogin:
    @pytest.mark.parametrize('logininfo', YamlUtil().read_testcase_yaml('v24.06/login/1_login.yaml'))
    def test_get_login(self, logininfo):
        # 1.触发管理面的登录功能
        baseUrl = datas.baseUrl
        url = baseUrl + logininfo['request']['url']
        method = logininfo['request']['method']
        req = RequestUtil().send_request(method, url)
        Location1 = req.headers['Location']
        # 2.生成用户授权码接口
        url2 = baseUrl + Location1
        req2 = RequestUtil().send_request('get', url2)
        Location2 = req2.headers['Location']
        # 3.获取用户登录界面接口
        url3 = baseUrl + Location2
        req3 = RequestUtil().send_request('get', url3)
        soup = BeautifulSoup(req3.text, 'html.parser')
        all_input_label = soup.find_all('input')
        for i in all_input_label:
            if i['name'] == 'gorilla.csrf.Token':
                gorilla_csrf_Token = i['value']
                print('打印gorilla_csrf_Token：', gorilla_csrf_Token)
            if i['name'] == 'then':
                get_then = i['value']
                print('打印then:', get_then)
        # 4.发送用户账号密码接口
        url4 = baseUrl + '/oauth2/auth/login/fuyaoPasswordProvider'
        header = {"Content-Type": "application/json", "X-Csrf-Token": gorilla_csrf_Token}
        password = [int(i) for i in datas.PASSWORD[1:-1].split(',')]
        data = {"username": datas.USERNAME, "password": password, "then": get_then}
        req4 = RequestUtil().send_request('post', url4, headers=header, json=data)
        Location3 = req4.headers['Location']
        # 5.生成用户授权码接口
        url5 = baseUrl + Location3
        req5 = RequestUtil().send_request('get', url5)
        Location4 = req5.headers['Location']
        # 6.授权code回调接口
        url6 = baseUrl + Location4
        req6 = RequestUtil().send_request('get', url6)
        # 7.检查登录成功
        url7 = baseUrl + '/'
        req7 = RequestUtil().send_request('get', url7)
        assert req7.status_code == 200


if __name__ == '__main__':
    pytest.main(["-s", "test_1login.py"])
